package lib.wman.org.mvp.presenter;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

import lib.wman.org.mvp.view.IDelegate;

/**
 * Created by Administrator on 2017/4/5.
 * Activity Presenter层的实现基类
 */

public abstract class ActivityPresenter<T extends IDelegate> extends AppCompatActivity {
    protected T mViewDelegate;

    public ActivityPresenter() {
        try {
            mViewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mViewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        setContentView(mViewDelegate.getRootView());
        initToolbar();
        mViewDelegate.initWidget();
        bindEventListener();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mViewDelegate == null) {
            try {
                mViewDelegate = getDelegateClass().newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("create IDelegate error");
            } catch (IllegalAccessException e) {
                throw new RuntimeException("create IDelegate error");
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mViewDelegate.getOptionsMenuId() != 0) {
            getMenuInflater().inflate(mViewDelegate.getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    protected abstract void bindEventListener();

    protected void initToolbar() {
        Toolbar toolbar = mViewDelegate.getToolBar();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewDelegate = null;
    }

    protected abstract Class<T> getDelegateClass();
}
